<template>
	<div class="organ-manage-container">
		<filterBar ref="filterBar" :factoryList="factoryList" @on-search="refresh"></filterBar>
		<w-table
			ref="listTable"
			:tableColumn="tableColumn"
			:listData="tableData"
			:showColumnFilterBtn="false"
			@on-size-change="handleSizeChange"
			@on-current-change="handleCurrentChange"
			@on-table-row-dbclick="onTableRowDbclick"
		>
			<div slot="btn-tools-right" class="tools-right">
				<el-button type="danger" plain size='mini' @click="mutileDel">删除</el-button>
				<el-button type="success" plain size='mini' @click="unExamine">反审</el-button>
				<el-button type="primary" plain size='mini' @click="examine">审核</el-button>
				<el-popover class="buttonMore"
					popper-class="dialog-tools-popover"
					placement="bottom"
					trigger="click">
					<div style="text-align:center;display:flex;flex-direction: column;">
						<el-button class="moreButton" type="primary" plain size='mini' @click="exportModel">导出模板</el-button>
						<el-button class="moreButton" type="primary" plain size='mini' @click="importPlan">导入</el-button>
						<el-button class="moreButton" type="primary" plain size='mini' @click="exportPlan">导出</el-button>
					</div>
					<fx-button type="more" size='mini' slot="reference">更多</fx-button>
					<!-- <el-button size='mini' slot="reference" class="more">更多</el-button> -->
				</el-popover>
				<el-button type="primary" size='mini' icon="el-icon-plus" @click="onCreateClick">新建生产计划</el-button>
				<el-button type="primary" size='mini' icon="el-icon-plus">SCM导入</el-button>
			</div>
		</w-table>
		<ImportPlan ref='importPlan' @on-refresh="refresh"></ImportPlan>
	</div>
</template>
<script>
import filterBar from './FilterBar.vue'
import FxListStateTag from '@/components/common/Fx-list-state-tag.vue'
import ImportPlan from './ImportPlan.vue'
import axios from 'axios'
export default {
	name: 'listContainer',
	props: {
		getCurrentNode: Function
	},
	components: {
		filterBar,
		ImportPlan
	},
	data () {
		return {
			tableColumn: [
				{ prop: 'code', label: '生产计划单号', required: true },
				{ prop: 'productionPlanDate', label: '生产计划日期', required: true, width: '160px' },
				{ prop: 'factoryName', label: '工厂', required: true },
				{
					prop: 'state',
					label: '生产状态',
					required: true,
					fxRender: this.stateRender
				},
				{
					prop: 'busState',
					label: '单据状态',
					required: true,
					fxRender: this.busStateRender
				},
				{
					prop: 'processingPercent',
					label: '加工进度',
					required: true,
					fxRender: this.processingPercentRender
				},
				{	prop: 'remark', label: '备注', required: true, showOverflowTooltip: true },
				{
					prop: 'modifyDate', label: '修改时间', required: true, width: '160px'
				},
				{
					prop: 'modifyUserName', label: '修改人', required: true
				},
				{
					prop: 'createDate', label: '制单时间', required: true, width: '160px'
				},
				{
					prop: 'createUserName', label: '制单人', required: true
				}
			],
			tableData: [],
			factoryList: []
		}
	},
	computed: {
		billState (val, key) {
			return (val, key) => {
				return this.$fxStateMiddleware.getStateObj('billState')(val)[key]
			}
		},
		state () {
			return (val, key) => {
				return this.$fxStateMiddleware.getStateObj('state')(val)[key]
			}
		}
	},
	methods: {
		refresh () {
			this.$refs.listTable.setPaginationCurrent(1)
			this.$refs.listTable.clearSelected()
			this.getFactoryListSelect()
			return this.productionPlanQuery()
		},
		handleSizeChange (val) {
			this.getListData()
		},
		handleCurrentChange (val) {
			this.getListData()
		},
		getSearchParams () {
			const params = {
				...this.$refs.filterBar.getFilterParams()
			}
			return {
				...this.$refs.listTable.getPaginationParams(),
				params: {
					...params
				}
			}
		},
		getFactoryListSelect () {
			return this.$fxApi('workshop.findFactoryList').then(res => {
				this.factoryList = res
				return Promise.resolve(res)
			})
		},
		productionPlanQuery (searchParams) {
			return this.$fxApi('schedule.productionPlanQuery')({ data: this.getSearchParams() }).then(res => {
				this.$refs.listTable.setPaginationTotal(res.total)
				this.tableData = res.data
				return Promise.resolve(res.data)
			})
		},
		onCreateClick () {
			this.$emit('on-create')
		},
		// 批量删除
		mutileDel () {
			const _selData = this.$refs.listTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('deleteMulity', _selData)
				.then(this.deleteMaterial)
				.then(this.refresh)
		},
		deleteMaterial () {
			const _selData = this.$refs.listTable.selectedRowArr
			const ids = []
			_selData.forEach((v) => {
				ids.push(v.id)
			})
			return new Promise(resolve => {
				this.$fxApi('schedule.batchDelete')({
					data: {
						ids: ids
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		// 反审
		unExamine () {
			this.$refs.listTable.getSelectedRows().then(res => {
				this.$fxConfirm('是否确定反审所选计划？').then(() => {
					this.onCheckHandler(res, 0)
				})
			})
		},
		// 审核
		examine () {
			this.$refs.listTable.getSelectedRows().then(res => {
				this.$fxConfirm('是否确定审核所选计划？').then(() => {
					this.onCheckHandler(res, 1)
				})
			})
		},
		onCheckHandler (selectRows, opertion) {
			const params = selectRows.map(item => {
				return item.id
			})
			return this.$fxApi('schedule.batchAudit')({
				data: {
					ids: params,
					opertion: opertion
				}
			}).then(res => {
				this.$emit('on-refresh')
				return Promise.resolve()
			})
		},
		busStateRender (h, { row }) {
			return <FxListStateTag
				icon={this.billState(row.busState, 'icon')}
				label={this.billState(row.busState, 'label')}
			></FxListStateTag>
		},
		stateRender (h, { row }) {
			return <FxListStateTag
				icon={this.state(row.state, 'icon')}
				label={this.state(row.state, 'label')}
			></FxListStateTag>
		},
		processingPercentRender (h, { row }) {
			return <el-progress percentage={row.processingPercent || 0}
			></el-progress>
		},
		onTableRowDbclick (item) {
			return Promise.all([this.getProgram(item.id), this.getProgramDetails(item.id)]).then(([plan, details]) => {
				this.$emit('on-edit', plan, details)
				return Promise.resolve()
			})
		},
		getProgram (planId) {
			return this.$fxApi('schedule.findDetailByParam')({
				query: {
					id: planId
				}
			}).then(res => {
				return Promise.resolve(res)
			})
		},
		getProgramDetails (planId) {
			return this.$fxApi('schedule.findProductionPlanDetail')({
				query: {
					productionPlanId: planId
				}
			}).then(res => {
				return Promise.resolve(res)
			})
		},
		// 导入
		importPlan () {
			this.$refs.importPlan.open()
		},
		// 导出模板
		exportModel () {
			var elemIF = document.createElement('iframe')
			elemIF.src = 'schedule/productionPlan/export/exportPlanTemplate'
			elemIF.style.display = 'none'
			document.body.appendChild(elemIF)
		},
		// 导出计划
		exportPlan () {
			const filterIds = this.$refs.listTable.getSelectIds()
			axios({
				method: 'post',
				url: 'schedule/productionPlan/export/exportPlan',
				data: {
					planIds: filterIds
				},
				responseType: 'blob'
			}).then((res) => {
				const blob = new Blob([res.data]) // Blob 对象表示一个不可变、原始数据的类文件对象
				const fileReader = new FileReader() // FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件的内容
				fileReader.readAsDataURL(blob)
				// 开始读取指定的Blob中的内容。一旦完成，result属性中将包含一个data: URL格式的Base64字符串以表示所读取文件的内容
				fileReader.onload = (e) => {
					const a = document.createElement('a')
					const fileName = '生产计划' + this.$fxUtils.setDate(new Date())
					a.download = fileName + '.xlsx'
					a.style.display = 'none'
					a.href = URL.createObjectURL(blob)
					document.body.appendChild(a)
					a.click()
					document.body.removeChild(a)
				}
			}).catch(err => {
				console.log(err)
			})
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl'
.organ-manage-container {
	flex: 1;
	display:flex
	flex-direction: column
	overflow: auto
	.tools-left, .tools-right {
		display:flex
		flex-direction: row
		align-items: center
	}
	.tools-left {
		flex: 1
	}
	.buttonMore {
		margin: 0 10px
	}
}
.el-popper {
	.moreButton {
		margin: 5px 0 0 10px
	}
}
.more {
	color: #fff
	background-color: $fxViolet1
}
</style>
